const fs = require('fs');
const path = require('path');
const archiver = require('archiver');

async function buildExtension() {
    const srcDir = path.join(__dirname, 'src');
    const distDir = path.join(__dirname, 'vega');

    // 1. 清理并创建目录
    if (fs.existsSync(distDir)) fs.rmSync(distDir, { recursive: true });
    fs.mkdirSync(distDir, { recursive: true });

    // 2. 复制所有文件 (跨平台方法)
    const copyRecursiveSync = (src, dest) => {
        if (fs.statSync(src).isDirectory()) {
            fs.mkdirSync(dest, { recursive: true });
            fs.readdirSync(src).forEach(file => {
                copyRecursiveSync(path.join(src, file), path.join(dest, file));
            });
        } else {
            fs.copyFileSync(src, dest);
        }
    };

    copyRecursiveSync(srcDir, distDir);

    // 3. 确保所有文件都有读取权限
    const setPermissions = (dir) => {
        fs.readdirSync(dir).forEach(file => {
            const fullPath = path.join(dir, file);
            if (fs.statSync(fullPath).isDirectory()) {
                setPermissions(fullPath);
            } else {
                fs.chmodSync(fullPath, '644');
            }
        });
    };
    setPermissions(distDir);

    // 4. 打包成ZIP
    const zipPath = path.join(__dirname, 'vega.v0.1.zip');
    const output = fs.createWriteStream(zipPath);
    const archive = archiver('zip', { zlib: { level: 9 } });

    await new Promise((resolve, reject) => {
        output.on('close', resolve);
        archive.on('error', reject);

        archive.pipe(output);
        archive.directory(distDir, false);
        archive.finalize();
    });

    console.log('✅ 扩展打包成功: ', zipPath);
    console.log('👉 在 Chrome 中: chrome://extensions');
    console.log('👉 拖放 dist 文件夹或 grafana-helper.zip 安装');
}

buildExtension().catch(console.error);
